package com.yitao.cms.service.user.cmsUser;


import com.skipper.base.service.GenericEntityService;
import com.yitao.cms.dto.operationUser.OperationRolePermissionDto;
import com.yitao.cms.enums.PermissionEnums;
import com.yitao.cms.model.operationUser.OperationRolePermissionModel;
import com.yitao.cms.model.operationUser.QOperationPermissionModel;
import com.yitao.cms.model.operationUser.QOperationRolePermissionModel;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.ArrayList;
import java.util.List;


@Service
public class OperationRolePermissionService extends GenericEntityService<OperationRolePermissionModel, OperationRolePermissionDto, QOperationRolePermissionModel> {
    public OperationRolePermissionService(EntityManager entityManager) {
        super(entityManager);
    }

    /**
     * 根据角色id查询资源(只展示子菜单)
     *
     * @param roleId
     * @return
     */
    public List<String> findPermissionByRoleId(Long roleId) {

        QOperationPermissionModel permissionModel = QOperationPermissionModel.operationPermissionModel;
        List<OperationRolePermissionModel> rolePermission= queryFactory.select(Q).from(Q).
                leftJoin(permissionModel).on(Q.permissionId.eq(permissionModel.id))
                .where(Q.roleId.eq(roleId).and(permissionModel.pathType.eq(PermissionEnums.pathType.SUBMENU.getCode())))
                .fetch();
        List<String> permissionIds=new ArrayList<>();
        for(OperationRolePermissionModel rolePermission1:rolePermission){
            permissionIds.add(String.valueOf(rolePermission1.getPermissionId()));
        }
        return permissionIds;
    }

    /**
     * 添加角色的权限
     * @param roleId
     * @param permissionIds
     */
    @Transactional
    public void addRolePermission(Long roleId, List<String> permissionIds) {
        repository.deleteByWhere(Q.roleId.eq(roleId));
        List<OperationRolePermissionModel> RolePermissionModels = new ArrayList<>();
        for (String permissionId : permissionIds) {
            OperationRolePermissionModel rolePermissionModel = new OperationRolePermissionModel();
            rolePermissionModel.setRoleId(Long.valueOf(roleId));
            rolePermissionModel.setPermissionId(Long.valueOf(permissionId));
            RolePermissionModels.add(rolePermissionModel);
        }
        repository.save(RolePermissionModels);
    }





}
